<template>
  <div class="permission">
    <el-card>
      <div style="text-align: right">
        <el-button
          type="primary"
          icon="el-icon-edit"
          @click="add('0', 1)"
        >添加菜单</el-button>
      </div>
      <el-table style="width: 100%" :data="tableData" row-key="id">
        <el-table-column label="菜单名称" prop="name">
          <template v-slot="{ row }">
            <i class="el-icon-folder-opened" />
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <div>
              <el-button
                v-if="row.type === 1"
                type="text"
                @click="add(row.id, 1)"
              >添加页面</el-button>
              <el-button
                v-if="row.type === 1"
                type="text"
                @click="add(row.id, 0)"
              >添加按钮</el-button>
              <el-button type="text" @click="edit(row)">查看 </el-button>
              <el-button type="text" @click="del(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增 -->
      <Add ref="ref" @getData="getData" />
    </el-card>
  </div>
</template>

<script>
import { sysPermission, sysPermissionDelete } from '@/api/permission'
import Add from './components/Add.vue'
export default {
  components: {
    Add
  },
  data() {
    return {
      tableData: []
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 获取权限数据并渲染
    async getData() {
      const res = await sysPermission()
      this.tableData = this.changeList(res.data, '0')
      // console.log(res.data)
    },
    // 树形数据结构
    changeList(arr, str) {
      // 找出第一次 item.pid === str
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeList(arr, item.id)
          return true
        }
      })
    },
    // 新增组件
    add(pid, type) {
      this.$refs.ref.showDialog = true
      this.$refs.ref.form.pid = pid
      this.$refs.ref.form.type = type
      this.$refs.ref.mode = 'add'
    },
    // 编辑组件
    edit(row) {
      this.$refs.ref.showDialog = true
      this.$refs.ref.mode = 'edit'
      this.$refs.ref.form = JSON.parse(JSON.stringify(row)) // 点击编辑时数据回显
    },
    // 删除
    del(row) {
      this.$confirm('是否删除当前权限', '提示', {
        type: 'warning'
      }).then(async() => {
        await sysPermissionDelete(row.id)
        this.$message.success('删除当前权限成功')
        this.getData()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 15px;
}
</style>
